<template>
    <div class="content">
        <el-dialog :visible.sync="batchBind.dialogFormVisible" title="购买激活码" size="tiny" :before-close="handleClose">
            <div v-loading = "upLoading">
                <el-form ref="ruleForm" :model="ruleForm" label-width="100px" :rules="rules">

                    <el-row>
                        <el-form-item label="">
                            <el-col :span="22">
                                <div class="tip">当前分成比例：<span v-cloak>{{(DividedPercentage) * 100}}</span>%</div>
                            </el-col>
                        </el-form-item>
                    </el-row>
                    <el-row>
                        <el-form-item label="学校：" prop="schoolName">
                            <el-col :span="22">
                                <school v-model="ruleForm.schoolName" style="width:100%" @getSchoolInfor = "schoolVerify"></school>
                            </el-col>
                        </el-form-item>
                    </el-row>
        
                    <el-row class="month">
                        <el-form-item label="月数：" prop="month">
                            <el-radio-group v-model="ruleForm.month" @change="changeMouth(monthList[$event])">
                                <el-col :span="11" v-for = "(item,index) in monthList" :key = "index">
                                    <el-radio class="monthItem" :label="index">{{item.name+'('+ item.price + '元)'}}</el-radio>
                                </el-col>
                            </el-radio-group>
                        </el-form-item>
                    </el-row>

                    <el-row>
                        <el-form-item label="个数：" prop="count">
                            <el-col :span="22">
                                <el-input type = 'number' :maxlength="3" v-model="ruleForm.count" placeholder="请输入个数" @change="changeCount"></el-input>
                                <div class="tip">线下应付金额：<span>{{toCount}}</span>元</div>
                            </el-col>
                        </el-form-item>
                    </el-row>
                    <el-row>
                        <el-form-item label="实付金额：" prop="pay">
                            <el-col :span="22">
                                <el-input type = 'number' v-model="ruleForm.pay" placeholder="请输入实付金额（元）"></el-input>
                                <div class="tip">若您参加了我们的活动，请在此修改您优惠后的实付金额，并在线下按此金额支付。</div>
                            </el-col>
                        </el-form-item>
                    </el-row>
                </el-form>
                <footer>
                    <el-button @click="cancel">取消</el-button>
                    <el-button @click="confirm('ruleForm')" type="primary">确认</el-button>
                </footer>
            </div>
        </el-dialog>
    </div>
</template>
<script>
import school from 'components/SchoolClasss/school';
import {
    listMembershipCharge,
    insertActivationCode
} from 'api/numberManagement';
export default {
    name: 'addClassSchool',
    components: { school },
    props: {
        batchBind: {
            type: Object,
            required: true
        }
    },
    data() {
        return {
            upLoading: false,
            ActivationList: [],
            DividedPercentage: '',
            membershipChargeId: '',
            monthItem: {
                sMonth: '',
                sUnitPrice: ''
            },
            monthList: [],
            schoolList: [],
            autoFill: false,
            ruleForm: {
                schoolName: '',
                schoolId: '',
                month: '',
                count: '',
                pay: ''
            },
            loading: false,
        
        // 是否培训和普通学校  1 0
            schoolType: '0',

            rulesSeletarea: {
                validator: (rule, value, callback) => {
                    if (!this.ruleForm.areaId && !value) {
                        callback(new Error('请选择'));
                    } else {
                        callback();
                    }
                },
                trigger: 'change'
            },
            rules: {
                schoolName: [
                    { required: true, message: '请输入关键词', trigger: 'blur' }
                ],
                pay: [
                    { required: true, message: '请输入实付金额', trigger: 'blur' },
                    // { pattern: /^[0-9]*$/, message: '请输入正确的金额', trigger: 'change' }
                    { pattern: /^\d+(\.\d{1,2})?$/, message: '实付金额大于等于0且最多可输入两位小数', trigger: 'change, blur' }
                    
                ],
                count: [
                    { required: true, message: '请输入个数', trigger: 'blur' },
                    { pattern: /^(?:[1-9]\d?|[1234]\d{2}|500)$/, message: '请输入1到500的整数', trigger: 'change, blur' }
                ],
                month: [{ required: true, type: 'number', message: '请选择月数', trigger: 'change' }]
            }
        };
    },
    computed: {
        toCount() {
            return (this.ruleForm.count != '' && this.ruleForm.count > 0) ? (this.ruleForm.count * this.monthItem.sUnitPrice * (1 - this.DividedPercentage)).toFixed(2) : 0.00.toFixed(2);
        }
    },
    created() {
        this.listMembershipCharge();
        
    },
    methods: {
        listMembershipCharge() {
            listMembershipCharge().then(data => {
                this.ActivationList = data.data.content[0];
                this.DividedPercentage = this.ActivationList.sDividedPercentage;
                this.membershipChargeId = this.ActivationList.pId;
                this.monthList = JSON.parse(this.ActivationList.sDetail);
            })
            .catch(Error => {
                this.upLoading = false;
                // this.$message(Error);
            });
        },
        schoolVerify(val) {
            if (val) {
                this.ruleForm.schoolId = val.pId;
                this.ruleForm.schoolName = val.sName;
            }
        },

        handleClose() {
            this.$refs.ruleForm.resetFields();
            this.ruleForm.month = '';
            this.monthItem.sUnitPrice = '';
            this.batchBind.dialogFormVisible = false;
        },
        changeMouth(item) {
            if (item) {
                this.monthItem.sMonth = item.value;
                this.monthItem.sUnitPrice = item.price;
            }
            if (this.ruleForm.count > 0) {
                this.ruleForm.pay = this.ruleForm.count * this.monthItem.sUnitPrice * (1 - this.DividedPercentage) != 0 ? String((this.ruleForm.count * this.monthItem.sUnitPrice * (1 - this.DividedPercentage)).toFixed(2)) : '';
            } else {
                this.ruleForm.pay = '';
            }
        },
        changeCount(num) {
            if (this.ruleForm.count > 0) {
                this.ruleForm.pay = this.ruleForm.count * this.monthItem.sUnitPrice * (1 - this.DividedPercentage) != 0 ? String((this.ruleForm.count * this.monthItem.sUnitPrice * (1 - this.DividedPercentage)).toFixed(2)) : '';
            } else {
                this.ruleForm.pay = '';
            }
        },
        confirm(ruleForm) {
            this.$refs[ruleForm].validate(valid => {
                if (!valid) {
                    return false;
                } else {
                    // if (this.ruleForm.schoolId) {
                    //     this.$message('请填写完整的信息');
                    //     return;
                    // }

                    if (this.ruleForm.schoolId === '') {
                        this.$message('请选择学校');
                        return;
                    }
                    
                    if (this.ruleForm.pay > this.ruleForm.count * this.monthItem.sUnitPrice * (1 - this.DividedPercentage)) {
                        this.$message({
                            message: '实付金额应小于等于应付金额',
                            type: 'info'
                        });
                        return;
                    }

                    this.upLoading = true;


                // this.$message("已经添加成功，请稍等更新~");
                // this.loading = false;
                // this.bindCard.dialogFormVisible = false;

                    // fSchoolId,
                    // sSchoolName,
                    // membershipChargeId,
                    // sPaid,
                    // sNumber,
                    // sPayable,
                    // sUnitPrice,
                    // sProportion,
                    // sMonth
                    insertActivationCode(
                        this.ruleForm.schoolId,
                        this.ruleForm.schoolName,
                        this.membershipChargeId,
                        this.ruleForm.pay,
                        this.ruleForm.count,
                        this.ruleForm.count * this.monthItem.sUnitPrice + '',
                        this.monthItem.sUnitPrice,
                        this.DividedPercentage,
                        this.monthItem.sMonth
                        
                    )
                    .then(data => {
                        this.upLoading = false;
                        this.batchBind.dialogFormVisible = false;
                    // 给父组件传值
                        this.$message({
                            message: '购买成功！',
                            type: 'success'
                        });
                        
                        this.cancel();
                        this.$emit('bindCardState');
                    })
                    .catch(Error => {
                        this.upLoading = false;
                        // this.$message(Error);
                    });
                }
            });
        },

        cancel() {
            this.$refs.ruleForm.resetFields();
            this.ruleForm.month = '';
            this.monthItem.sUnitPrice = '';
            this.batchBind.dialogFormVisible = false;
        }
    },
    watch: {
        ['batchBind.dialogFormVisible'](val) { 
            if (val) {
                this.listMembershipCharge();
            }
        }
    }
};
</script>
<style lang="scss" scoped>
.title {
  display: block;
  text-align: left;
  margin-left: 20px;
  font-size: 14px;
  margin-bottom: 18px;
  color: #333;
  position: relative;
  &::after {
    position: absolute;
    width: 4px;
    height: 14px;
    background: #ff5e2c;
    left: -15px;
    top: 10px;
    content: "";
  }
}
.monthItem{
    width: 150px;
    margin-left: 0;
    margin-right: 30px;
    padding: 2px 0;
}
// .monthItem:nth-child(3n+1){
//     margin-left: 0;
// }
.tip{
  padding: 5px 0;
  color: #666;
  line-height: 18px;
}
footer {
  text-align: center;
}
.month{
    margin-top:10px;
}
</style>
